using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Bom;
using WPF_MVVM_Test.MVVM_Model.Process;
using WPF_MVVM_Test.MVVM_View.Bom;
using WPF_MVVM_Test.Services.Process;

namespace WPF_MVVM_Test.MVVM_ViewModel.Bom
{
    /// <summary>
    /// BOM新增页面的ViewModel
    /// </summary>
    public class BomAddViewModel : BaseViewModel
    {
        private string _bomNumber = "";
        private string _systemNumber = "";
        private bool _isDefaultBom = true;
        private string _bomVersion = "";
        private string _productName = "";
        private string _productNumber = "";
        private string _specification = "";
        private string _unit = "";
        private string _dailyOutput = "";
        private string _remark = "";
        private ObservableCollection<MaterialSelectionItem> _materialItems;
        private MaterialSelectionItem? _selectedMaterialItem;

        // 工艺路线相关属性
        private string _processRouteId = "";
        private string _processRouteName = "";
        private string _processRouteNumber = "";

        // 工序相关属性
        private ObservableCollection<ProcessStepModel> _processStepList;
        private readonly ProcessStepService _processStepService;

        // 工序物料相关属性
        private ObservableCollection<ProcessStepMaterialModel> _processStepMaterialList;
        private ProcessStepModel? _selectedProcessStep;
        private string _currentProcessStepName = "请选择工序";

        // 服务
        private readonly Services.Bom.BomService _bomService;

        /// <summary>
        /// 页面导航事件 - 用于通知主窗口切换页面并刷新数据
        /// </summary>
        public static event Action<string, bool>? RequestNavigateToPageWithRefresh;

        /// <summary>
        /// 构造函数
        /// </summary>
        public BomAddViewModel()
        {
            // 初始化集合
            _materialItems = new ObservableCollection<MaterialSelectionItem>();
            _processStepList = new ObservableCollection<ProcessStepModel>();
            _processStepMaterialList = new ObservableCollection<ProcessStepMaterialModel>();

            // 初始化服务
            _processStepService = new ProcessStepService();
            _bomService = new Services.Bom.BomService();

            // 初始化命令
            SelectProductCommand = CreateCommand(ExecuteSelectProduct);
            AddMaterialCommand = CreateCommand(ExecuteAddMaterial);
            RemoveMaterialCommand = CreateCommand(ExecuteRemoveMaterial, CanExecuteRemoveMaterial);
            RemoveSingleMaterialCommand = CreateCommand<MaterialSelectionItem>(ExecuteRemoveSingleMaterial);

            // 工艺路线相关命令
            SelectProcessRouteCommand = CreateCommand(ExecuteSelectProcessRoute);
            ClearProcessRouteCommand = CreateCommand(ExecuteClearProcessRoute);

            // 工序相关命令
            SelectProcessStepCommand = CreateCommand<ProcessStepModel>(ExecuteSelectProcessStep);

            // 保存相关命令
            SaveBomCommand = CreateCommand(ExecuteSaveBom, CanExecuteSaveBom);
            CancelCommand = CreateCommand(ExecuteCancel);

            // 生成系统编号（示例）
            SystemNumber = $"SYS{DateTime.Now:yyyyMMddHHmmss}";
        }

        #region 属性

        /// <summary>
        /// BOM编号
        /// </summary>
        public string BomNumber
        {
            get => _bomNumber;
            set => SetProperty(ref _bomNumber, value);
        }

        /// <summary>
        /// 系统编号（只读）
        /// </summary>
        public string SystemNumber
        {
            get => _systemNumber;
            set => SetProperty(ref _systemNumber, value);
        }

        /// <summary>
        /// 是否默认BOM
        /// </summary>
        public bool IsDefaultBom
        {
            get => _isDefaultBom;
            set => SetProperty(ref _isDefaultBom, value);
        }

        /// <summary>
        /// BOM版本（只读，从产品选择后自动填充）
        /// </summary>
        public string BomVersion
        {
            get => _bomVersion;
            set => SetProperty(ref _bomVersion, value);
        }

        /// <summary>
        /// 产品名称
        /// </summary>
        public string ProductName
        {
            get => _productName;
            set => SetProperty(ref _productName, value);
        }

        /// <summary>
        /// 产品编号（只读，从产品选择后自动填充）
        /// </summary>
        public string ProductNumber
        {
            get => _productNumber;
            set => SetProperty(ref _productNumber, value);
        }

        /// <summary>
        /// 规格型号（只读，从产品选择后自动填充）
        /// </summary>
        public string Specification
        {
            get => _specification;
            set => SetProperty(ref _specification, value);
        }

        /// <summary>
        /// 单位（只读，从产品选择后自动填充）
        /// </summary>
        public string Unit
        {
            get => _unit;
            set => SetProperty(ref _unit, value);
        }

        /// <summary>
        /// 日产量
        /// </summary>
        public string DailyOutput
        {
            get => _dailyOutput;
            set => SetProperty(ref _dailyOutput, value);
        }

        /// <summary>
        /// 备注
        /// </summary>
        public string Remark
        {
            get => _remark;
            set => SetProperty(ref _remark, value);
        }

        /// <summary>
        /// 物料项列表
        /// </summary>
        public ObservableCollection<MaterialSelectionItem> MaterialItems
        {
            get => _materialItems;
            set => SetProperty(ref _materialItems, value);
        }

        /// <summary>
        /// 选中的物料项
        /// </summary>
        public MaterialSelectionItem? SelectedMaterialItem
        {
            get => _selectedMaterialItem;
            set
            {
                SetProperty(ref _selectedMaterialItem, value);
                (RemoveMaterialCommand as RelayCommand)?.RaiseCanExecuteChanged();
            }
        }

        /// <summary>
        /// 工艺路线ID
        /// </summary>
        public string ProcessRouteId
        {
            get => _processRouteId;
            set => SetProperty(ref _processRouteId, value);
        }

        /// <summary>
        /// 工艺路线名称
        /// </summary>
        public string ProcessRouteName
        {
            get => _processRouteName;
            set => SetProperty(ref _processRouteName, value);
        }

        /// <summary>
        /// 工艺路线编号
        /// </summary>
        public string ProcessRouteNumber
        {
            get => _processRouteNumber;
            set => SetProperty(ref _processRouteNumber, value);
        }

        /// <summary>
        /// 工序列表
        /// </summary>
        public ObservableCollection<ProcessStepModel> ProcessStepList
        {
            get => _processStepList;
            set => SetProperty(ref _processStepList, value);
        }

        /// <summary>
        /// 工序物料列表
        /// </summary>
        public ObservableCollection<ProcessStepMaterialModel> ProcessStepMaterialList
        {
            get => _processStepMaterialList;
            set => SetProperty(ref _processStepMaterialList, value);
        }

        /// <summary>
        /// 选中的工序
        /// </summary>
        public ProcessStepModel? SelectedProcessStep
        {
            get => _selectedProcessStep;
            set => SetProperty(ref _selectedProcessStep, value);
        }

        /// <summary>
        /// 当前工序名称
        /// </summary>
        public string CurrentProcessStepName
        {
            get => _currentProcessStepName;
            set => SetProperty(ref _currentProcessStepName, value);
        }

        #endregion

        #region 命令

        /// <summary>
        /// 选择产品命令
        /// </summary>
        public ICommand SelectProductCommand { get; }

        /// <summary>
        /// 添加物料命令
        /// </summary>
        public ICommand AddMaterialCommand { get; }

        /// <summary>
        /// 移除物料命令
        /// </summary>
        public ICommand RemoveMaterialCommand { get; }

        /// <summary>
        /// 移除单个物料命令
        /// </summary>
        public ICommand RemoveSingleMaterialCommand { get; }

        /// <summary>
        /// 选择工艺路线命令
        /// </summary>
        public ICommand SelectProcessRouteCommand { get; }

        /// <summary>
        /// 清除工艺路线命令
        /// </summary>
        public ICommand ClearProcessRouteCommand { get; }

        /// <summary>
        /// 选择工序命令
        /// </summary>
        public ICommand SelectProcessStepCommand { get; }

        /// <summary>
        /// 保存BOM命令
        /// </summary>
        public ICommand SaveBomCommand { get; }

        /// <summary>
        /// 取消命令
        /// </summary>
        public ICommand CancelCommand { get; }

        #endregion

        #region 命令执行方法

        /// <summary>
        /// 执行选择产品
        /// </summary>
        private void ExecuteSelectProduct()
        {
            try
            {
                // 创建产品选择窗口
                var productSelectWindow = new Window
                {
                    Title = "选择产品",
                    Width = 700,
                    Height = 500,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    ResizeMode = ResizeMode.NoResize
                };

                // 创建产品选择UserControl
                var productSelectDialog = new WPF_MVVM_Test.MVVM_View.Bom.ProductSelectDialog();
                productSelectWindow.Content = productSelectDialog;

                // 显示对话框
                var result = productSelectWindow.ShowDialog();

                if (result == true)
                {
                    // 从对话框获取选中的产品信息
                    var selectedProduct = productSelectDialog.SelectedProduct;

                    if (selectedProduct != null)
                    {
                        // 自动填充产品相关信息
                        ProductName = selectedProduct.MaterialName;
                        BomVersion = "1.0";
                        ProductNumber = selectedProduct.MaterialNumber;
                        Specification = selectedProduct.SpecificationModel;
                        Unit = selectedProduct.Unit;

                        // 添加这行来设置产品ID
                        SelectedProductId = selectedProduct.Id; // 需要添加这行
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show($"执行选择产品时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 执行添加物料
        /// </summary>
        private void ExecuteAddMaterial()
        {
            try
            {
                var dialog = new MaterialSelectionDialog();
                var result = dialog.ShowDialog();

                if (result == true)
                {
                    var selectedBomItems = dialog.SelectedBomItems;

                    if (selectedBomItems != null && selectedBomItems.Count > 0)
                    {
                        foreach (var bomItem in selectedBomItems)
                        {
                            // 检查是否已存在相同的物料
                            var existingItem = MaterialItems.FirstOrDefault(x => x.Id == bomItem.MaterialId);
                            if (existingItem == null)
                            {
                                // 从BomItemModel转换为MaterialSelectionItem用于显示
                                var materialItem = new MaterialSelectionItem
                                {
                                    Id = bomItem.MaterialId,
                                    MaterialName = "物料名称", // 这里需要从物料ID获取物料信息
                                    MaterialNumber = "物料编号", // 这里需要从物料ID获取物料信息
                                    SpecificationModel = "规格型号", // 这里需要从物料ID获取物料信息
                                    Unit = bomItem.Unit,
                                    Quantity = bomItem.Quantity,
                                    LossRate = bomItem.LossRate,
                                    Remark = bomItem.Remark,
                                    IsSelected = false
                                };

                                MaterialItems.Add(materialItem);
                            }
                            else
                            {
                                // 如果已存在，更新数量
                                existingItem.Quantity += bomItem.Quantity;
                            }
                        }

                        MessageBox.Show($"成功添加 {selectedBomItems.Count} 个物料！", "提示",
                            MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加物料时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 执行移除物料（批量移除选中的）
        /// </summary>
        private void ExecuteRemoveMaterial()
        {
            try
            {
                var selectedItems = MaterialItems.Where(x => x.IsSelected).ToList();

                if (selectedItems.Count == 0)
                {
                    MessageBox.Show("请先选择要移除的物料！", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                var result = MessageBox.Show($"确定要移除选中的 {selectedItems.Count} 个物料吗？", "确认移除",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    foreach (var item in selectedItems)
                    {
                        MaterialItems.Remove(item);
                    }

                    MessageBox.Show($"成功移除 {selectedItems.Count} 个物料！", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"移除物料时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 是否可以执行移除物料命令
        /// </summary>
        private bool CanExecuteRemoveMaterial()
        {
            return MaterialItems?.Any(x => x.IsSelected) == true;
        }

        /// <summary>
        /// 执行移除单个物料
        /// </summary>
        private void ExecuteRemoveSingleMaterial(MaterialSelectionItem? item)
        {
            if (item == null) return;

            try
            {
                var result = MessageBox.Show($"确定要移除物料 \"{item.MaterialName}\" 吗？", "确认移除",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    MaterialItems.Remove(item);
                    MessageBox.Show("物料移除成功！", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"移除物料时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 获取BOM项列表（用于保存）
        /// </summary>
        public System.Collections.Generic.List<BomItemModel> GetBomItems()
        {
            var bomItems = new System.Collections.Generic.List<BomItemModel>();

            foreach (var item in MaterialItems)
            {
                bomItems.Add(new BomItemModel
                {
                    MaterialId = item.Id,
                    ParentItemId = Guid.Empty.ToString(), // 根据需要设置
                    Quantity = item.Quantity,
                    LossRate = item.LossRate,
                    InOutType = 1,
                    Unit = item.Unit,
                    Remark = item.Remark
                });
            }

            return bomItems;
        }

        /// <summary>
        /// 执行选择工艺路线
        /// </summary>
        private async void ExecuteSelectProcessRoute()
        {
            try
            {
                var dialog = new ProcessRouteSelectionDialog();
                var result = dialog.ShowDialog();

                if (result == true)
                {
                    var selectedProcessRoute = dialog.SelectedProcessRoute;

                    if (selectedProcessRoute != null)
                    {
                        ProcessRouteId = selectedProcessRoute.Id;
                        ProcessRouteName = selectedProcessRoute.ProcessRouteName;
                        ProcessRouteNumber = selectedProcessRoute.ProcessRouteNumber;

                        // 选择工艺路线后，自动加载工序
                        await LoadProcessStepsAsync(selectedProcessRoute.Id);

                        MessageBox.Show($"已选择工艺路线：{selectedProcessRoute.ProcessRouteName}", "提示",
                            MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择工艺路线时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 执行清除工艺路线
        /// </summary>
        private void ExecuteClearProcessRoute()
        {
            try
            {
                var result = MessageBox.Show("确定要清除当前选择的工艺路线吗？", "确认清除",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    ProcessRouteId = "";
                    ProcessRouteName = "";
                    ProcessRouteNumber = "";

                    // 清除工序列表和物料列表
                    ProcessStepList.Clear();
                    ProcessStepMaterialList.Clear();
                    CurrentProcessStepName = "请选择工序";

                    MessageBox.Show("工艺路线已清除！", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"清除工艺路线时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 加载工序列表
        /// </summary>
        /// <param name="processRouteId">工艺路线ID</param>
        private async Task LoadProcessStepsAsync(string processRouteId)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"开始加载工序数据，工艺路线ID: {processRouteId}");

                var response = await _processStepService.GetProcessStepsByRouteIdAsync(processRouteId);

                if (response.IsSuc)
                {
                    System.Diagnostics.Debug.WriteLine($"工序数据加载成功，数据数量: {response.Data.Count}");

                    ProcessStepList.Clear();
                    foreach (var step in response.Data)
                    {
                        ProcessStepList.Add(step);
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"工序数据加载失败: {response.Msg}，使用测试数据");
                    LoadTestProcessSteps();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"工序数据加载异常: {ex.Message}，使用测试数据");
                LoadTestProcessSteps();
            }
        }

        /// <summary>
        /// 加载测试工序数据
        /// </summary>
        private void LoadTestProcessSteps()
        {
            ProcessStepList.Clear();

            var testSteps = new[]
            {
                new ProcessStepModel
                {
                    Id = "ebcb19b6-c58e-43dd-a67e-6d3c3b471196",
                    ProcessStepName = "原料预处理"
                },
                new ProcessStepModel
                {
                    Id = "b624d91e-99e2-47ed-832f-c07ef55fac39",
                    ProcessStepName = "主加工"
                },
                new ProcessStepModel
                {
                    Id = "21eef898-8cf9-45db-9e3d-4c7b909eda42",
                    ProcessStepName = "精加工"
                },
                new ProcessStepModel
                {
                    Id = "543a24ae-7946-4ac8-aa0a-a9680acc5b01",
                    ProcessStepName = "检验"
                },
                new ProcessStepModel
                {
                    Id = "9fba4351-cdec-4a73-904f-889ab2051625",
                    ProcessStepName = "包装"
                }
            };

            foreach (var step in testSteps)
            {
                ProcessStepList.Add(step);
            }
        }

        /// <summary>
        /// 执行选择工序 - 每次点击都重新从数据库获取最新物料数据
        /// </summary>
        /// <param name="processStep">选中的工序</param>
        private async void ExecuteSelectProcessStep(ProcessStepModel? processStep)
        {
            if (processStep == null) return;

            try
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 用户点击工序: {processStep.ProcessStepName} (ID: {processStep.Id})");

                // 清除之前选中的工序
                foreach (var step in ProcessStepList)
                {
                    step.IsSelected = false;
                }

                // 设置当前选中的工序
                processStep.IsSelected = true;
                SelectedProcessStep = processStep;

                // 显示加载状态
                CurrentProcessStepName = $"工序：{processStep.ProcessStepName} (正在从数据库加载最新数据...)";

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 开始从数据库加载工序物料，确保获取最新数据");

                // 每次点击都重新从数据库加载该工序的最新物料数据
                await LoadProcessStepMaterialsAsync(processStep.Id);

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序物料数据加载完成");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 选择工序时发生错误: {ex.Message}");
                CurrentProcessStepName = $"工序：{processStep.ProcessStepName} (加载失败)";
                MessageBox.Show($"选择工序时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 加载工序物料列表 - 每次都从数据库获取最新数据
        /// </summary>
        /// <param name="processStepId">工序ID</param>
        private async Task LoadProcessStepMaterialsAsync(string processStepId)
        {
            try
            {
                // 先清空当前物料列表，显示加载状态
                ProcessStepMaterialList.Clear();
                CurrentProcessStepName = $"工序：{SelectedProcessStep?.ProcessStepName} (加载中...)";

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 开始从数据库加载工序物料数据，工序ID: {processStepId}");

                // 每次都重新从数据库获取最新数据
                var response = await _processStepService.GetProcessStepMaterialsAsync(processStepId);

                if (response.IsSuc)
                {
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序物料数据加载成功，数据数量: {response.Data.Count}");

                    // 更新UI显示
                    CurrentProcessStepName = $"工序：{SelectedProcessStep?.ProcessStepName} ({response.Data.Count}个物料)";

                    // 添加新数据
                    foreach (var material in response.Data)
                    {
                        ProcessStepMaterialList.Add(material);
                    }

                    // 如果没有物料数据，显示提示
                    if (response.Data.Count == 0)
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 该工序暂无物料数据");
                        CurrentProcessStepName = $"工序：{SelectedProcessStep?.ProcessStepName} (暂无物料)";
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 工序物料数据加载失败: {response.Msg}，使用测试数据");
                    CurrentProcessStepName = $"工序：{SelectedProcessStep?.ProcessStepName} (加载失败，显示测试数据)";
                    LoadTestProcessStepMaterials();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"工序物料数据加载异常: {ex.Message}，使用测试数据");
                LoadTestProcessStepMaterials();
            }
        }

        /// <summary>
        /// 加载测试工序物料数据
        /// </summary>
        private void LoadTestProcessStepMaterials()
        {
            ProcessStepMaterialList.Clear();

            var testMaterials = new[]
            {
                new ProcessStepMaterialModel
                {
                    Id = "0050bdd4-c2d3-4c0a-9075-9ed8b800fa40",
                    MaterialNumber = "PVC-ELE-001",
                    MaterialName = "电气用硬PVC管",
                    SpecificationModel = "Φ20×2.0mm",
                    Unit = "米",
                    MaterialType = 1,
                    MaterialProperty = "外购",
                    Status = "启用",
                    PurchasePrice = 8.5m,
                    SalesPrice = 12.8m,
                    Remarks = "阻燃等级B1，适用于室内电气线路保护"
                },
                new ProcessStepMaterialModel
                {
                    Id = "48c19b28-20f3-4b40-9696-243770b7b5e7",
                    MaterialNumber = "PVC-AUTO-002",
                    MaterialName = "汽车内饰软PVC薄膜",
                    SpecificationModel = "1.2mm×1500mm",
                    Unit = "平方米",
                    MaterialType = 1,
                    MaterialProperty = "外购",
                    Status = "启用",
                    PurchasePrice = 25.6m,
                    SalesPrice = 38.9m,
                    Remarks = "符合汽车内饰环保标准，具有良好的柔韧性和耐磨性，适用于座椅、门板等内饰件"
                }
            };

            foreach (var material in testMaterials)
            {
                ProcessStepMaterialList.Add(material);
            }
        }

        /// <summary>
        /// 执行保存BOM
        /// </summary>
        private async void ExecuteSaveBom()
        {
            try
            {
                // 显示保存确认对话框
                var result = MessageBox.Show("确定要保存当前BOM吗？", "确认保存",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result != MessageBoxResult.Yes)
                    return;

                // 验证必填字段
                if (!ValidateRequiredFields())
                    return;

                // 构建保存请求
                var bomRequest = BuildBomRequest();

                // 调用API保存
                var response = await _bomService.AddBomAsync(bomRequest);

                if (response.IsSuc)
                {
                    MessageBox.Show("BOM保存成功！", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);

                    // 保存成功后清空表单
                    ClearForm();

                    // 触发导航事件，回到BOM管理列表页面并刷新数据
                    RequestNavigateToPageWithRefresh?.Invoke("Bom管理", true);
                }
                else
                {
                    MessageBox.Show($"BOM保存失败：{response.Msg}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存BOM时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 是否可以执行保存BOM命令
        /// </summary>
        private bool CanExecuteSaveBom()
        {
            return !string.IsNullOrWhiteSpace(BomNumber) &&
                   !string.IsNullOrWhiteSpace(ProductName);
        }

        /// <summary>
        /// 执行取消
        /// </summary>
        private void ExecuteCancel()
        {
            try
            {
                var result = MessageBox.Show("确定要取消当前操作吗？未保存的数据将丢失。", "确认取消",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    ClearForm();

                    // 触发导航事件，回到BOM管理列表页面
                    RequestNavigateToPageWithRefresh?.Invoke("Bom管理", false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"取消操作时发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 验证必填字段
        /// </summary>
        private bool ValidateRequiredFields()
        {
            var errors = new List<string>();

            if (string.IsNullOrWhiteSpace(BomNumber))
                errors.Add("BOM编号不能为空");

            if (string.IsNullOrWhiteSpace(ProductName))
                errors.Add("产品名称不能为空");

            if (string.IsNullOrWhiteSpace(BomVersion))
                errors.Add("BOM版本不能为空");

            if (errors.Count > 0)
            {
                var errorMessage = "请完善以下必填信息：\n" + string.Join("\n", errors);
                MessageBox.Show(errorMessage, "验证失败",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 构建BOM保存请求
        /// </summary>
        private BomAddRequestModel BuildBomRequest()
        {
            var bomRequest = new BomAddRequestModel
            {
                BomNumber = BomNumber,
                IsSystemNumber = true,
                IsDefault = IsDefaultBom,
                Version = BomVersion,
                ProductId = SelectedProductId, // 修改：使用实际的产品ID
                ProductName = ProductName,
                ColorCode = "#FF5733", // 修改：可以添加颜色选择功能，或使用默认值
                Unit = Unit,
                DailyOutput = double.TryParse(DailyOutput, out var output) ? output : 0,
                Remark = Remark,
                ProcessRouteId = ProcessRouteId,
                BomItems = new List<BomAddItemModel>()
            };

            // 添加物料项
            foreach (var materialItem in MaterialItems)
            {
                bomRequest.BomItems.Add(new BomAddItemModel
                {
                    MaterialId = materialItem.Id,
                    ParentItemId = SelectedProductId, // 修改：使用产品ID作为父项ID
                    Quantity = (double)materialItem.Quantity,
                    LossRate = (double)materialItem.LossRate,
                    InOutType = 1,
                    Unit = materialItem.Unit,
                    Remark = materialItem.Remark
                });
            }

            return bomRequest;
        }

        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            BomNumber = "";
            IsDefaultBom = true;
            BomVersion = "";
            ProductName = "";
            ProductNumber = "";
            Specification = "";
            Unit = "";
            DailyOutput = "";
            Remark = "";

            ProcessRouteId = "";
            ProcessRouteName = "";
            ProcessRouteNumber = "";

            MaterialItems.Clear();
            ProcessStepList.Clear();
            ProcessStepMaterialList.Clear();
            CurrentProcessStepName = "请选择工序";

            // 重新生成系统编号
            SystemNumber = $"SYS{DateTime.Now:yyyyMMddHHmmss}";

            // 刷新命令状态
            (SaveBomCommand as RelayCommand)?.RaiseCanExecuteChanged();
        }

        /// <summary>
        /// 属性变更时刷新保存命令状态
        /// </summary>
        protected override void OnPropertyChanged(string propertyName)
        {
            base.OnPropertyChanged(propertyName);

            if (propertyName == nameof(BomNumber) || propertyName == nameof(ProductName))
            {
                (SaveBomCommand as RelayCommand)?.RaiseCanExecuteChanged();
            }
        }

        #endregion


        // 选中的产品ID
        private string _selectedProductId = "";

        /// <summary>
        /// 选中的产品ID
        /// </summary>
        public string SelectedProductId
        {
            get => _selectedProductId;
            set => SetProperty(ref _selectedProductId, value);
        }

    }


}

